package net.sinmetal.twitcockpit.controller.cockpit.schedule;

import java.util.List;

import net.sinmetal.twitcockpit.form.cockpit.schedule.AutoPostForm;
import net.sinmetal.twitcockpit.model.AutoPost;
import net.sinmetal.twitcockpit.modelvar.AutoPostVar;
import net.sinmetal.twitcockpit.service.AutoPostService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.util.BeanUtil;

/**
 * CockpitScheduleEditController
 *
 * @author Sinmetal
 *
 */
public class EditController extends Controller {

    private AutoPostService service = new AutoPostService();

    /**
     * 定期Post編集画面表示
     */
    @Override
    public Navigation run() throws Exception {
        String hour = requestScope("hour");
        String minute = requestScope("minute");
        String id = requestScope("id");

        AutoPostVar target = null;
        AutoPost autoPost =
            service.get(Integer.valueOf(hour), Integer.valueOf(minute));
        List<AutoPostVar> autoPostVars = autoPost.getAutoPostVars();
        for (AutoPostVar autoPostVar : autoPostVars) {
            if (id.equals(autoPostVar.getId())) {
                target = autoPostVar;
                break;
            }
        }

        if (target == null) {
            throw new RuntimeException(String.format("データがありません。id=%s", id));
        }
        AutoPostForm form = AutoPostForm.getInstance(target);
        BeanUtil.copy(form, request);
        return forward("edit.jsp");
    }
}
